# 导入正则模块
from re import compile
# 导入类视图
from django.views import View
# 导入模型类
from users.models import *
# 导入生成用户id函数
from common.user.userId import get_uuid
# 导入验证参数函数
from common.user.schema import check_data
# 导入判断数据是否注册函数
from common.user.schema import check_exist
# 导入加密密码函数
from common.user.encrypt import pass_encrypt
# 导入解密密码函数
from common.user.encrypt import pass_decode
# 导入生成token函数
from common.user.token import *
# 导入生成手机验证码函数
from common.user.code import *
# 导入响应数据函数
from common.respond.res import res

# Create your views here.

# 验证码
code = 0


# 发送注册验证码
def send_reg_code(request):
    # 验证码类型
    type_id = "注册验证码"
    # 验证码
    phone = request.GET.get("phone")
    if phone:
        if Users.objects.filter(phone=phone).exists():
            return res(400, "发送失败！", {'err': "手机号已注册！"})
        # 调用注册验证码
        data = log_codes(phone, type_id)
        if data:
            # 响应数据
            return res(200, "发送成功！", {'time': int(time.time()), "phone": phone})
    else:
        # 响应数据
        return res(400, "发送失败！", {'err': "手机号不能为空！"})


# 发送登录验证码
def send_log_code(request):
    # 验证码类型
    type_id = "登录验证码"
    # 手机号
    phone = request.GET.get("phone")
    # 验证手机号
    if compile(r'^1[34578]\d{9}$').match(phone):
        # 判断手机号注册没
        if not Users.objects.filter(phone=phone).exists():
            return res(400, "发送失败！", {'err': "手机号未注册！"})
        # 调用发送验证码方法
        data = log_codes(phone, type_id)
        if data:
            # 发送成功
            return res(200, "发送成功！", {'time': int(time.time()), "phone": phone})
    elif not phone:
        # 手机号为空
        return res(400, "发送失败！", {'err': "手机号不能为空！"})
    elif not compile(r'^1[34578]\d{9}$').match(phone):
        # 手机号格式错误
        return res(400, "发送失败！", {'err': "手机号格式错误！"})


# 用户注册接口
class Register(View):
    # 发送验证码
    def get(self, request):
        # 响应数据
        return res(200, "OK", "操作成功！")

    def post(self, request):
        # 获取注册的参数
        userinfo = eval(request.body.decode())
        # 用户昵称
        nickname = userinfo.get('nickName')
        # 用户密码
        pass_str = userinfo.get('passStr')
        # 用户手机号
        phone = userinfo.get('phone')
        # 注册验证码
        code_num = userinfo.get('code')
        # 验证数据是否符合要求
        ret = check_data(nickname, pass_str, phone)
        # 判断是否验证正确
        if ret['ret']:
            # 判断数据是否已被注册
            data = check_exist(nickname, phone)
            if data['ret']:
                # 取出当前手机号验证码表
                code_data = Code.objects.get(phone=phone)
                # 判断验证码是否正确
                if code_num == code_data.reg_code:
                    # 生成用户id
                    user_id = get_uuid()
                    # 将密码加密
                    password = pass_encrypt(pass_str)
                    # 注册用户
                    Users(userId=user_id, nickName=nickname, passStr=pass_str, password=password,
                          phone=phone).save()
                    user = list(
                        Users.objects.filter(userId=user_id, nickName=nickname, passStr=pass_str, password=password,
                                             phone=phone, time_stamp=int(time.time())).values())
                    # 注册成功
                    return res(200, "注册成功！", {'userInfo': user})
                else:
                    return res(400, "注册失败！", {'err': "验证码错误，请重新输入！"})
            else:
                return res(400, "注册失败！", {'err': data['name']})
        else:
            return res(400, "注册失败！", {'err': ret['name']})


# 用户登录接口
class Login(View):
    def get(self, request):
        # 响应数据
        return res(200, "OK", "操作成功！")

    def post(self, request):
        userinfo = eval(request.body.decode())
        print(userinfo)
        # 获取登录参数
        phone = userinfo["phone"]
        password = userinfo["password"]
        # 判断手机号是否已注册
        if Users.objects.filter(phone=phone).exists():
            # 获取登录的用户
            user = list(Users.objects.filter(phone=phone).values())
            # 判断密码是否正确
            pass_flag = pass_decode(password, user[0]['password'])
            if pass_flag:
                # 密码正确后，生成token
                token = get_token(user[0])
                # 查询登录用户
                users = Users.objects.get(phone=phone)
                # 添加登录token
                users.token = "Bearer " + token
                users.save()  # 保存
                # 将token保存到用户信息中
                user[0]['token'] = "Bearer " + token
                # 将明文密码清空
                user[0]['passStr'] = ''
                return res(200, "登录成功！", {'user': user})
            else:
                # 登录失败
                return res(400, "登录失败！", {'err': "密码错误，请重新输入！"})
        else:
            # 登录失败
            return res(400, "登录失败！", {'err': "手机号未注册！"})


# 验证码登录
class CodeLogin(View):
    def post(self, request):
        # 登录参数
        log_data = eval(request.body.decode())
        phone = log_data['phone']
        password = log_data['password']  # 验证码
        # 先判断手机号注册
        if Users.objects.filter(phone=phone).exists():
            # 取出当前手机号验证码表
            code_data = Code.objects.get(phone=phone)
            # 判断是否过期
            if int(time.time()) > int(code_data.time):
                return res(400, "登录失败！", {'user': "验证码已过期，请重新发送！"})
            else:
                # 判断验证码是否正确
                if password == code_data.code:
                    # 获取登录的用户
                    user = list(Users.objects.filter(phone=phone).values())
                    # 密码正确后，生成token
                    token = get_token(user[0])
                    # 查询登录用户
                    users = Users.objects.get(phone=phone)
                    # 添加登录token
                    users.token = "Bearer " + token
                    users.save()  # 保存
                    # 将token保存到用户信息中
                    user[0]['token'] = "Bearer " + token
                    # 将明文密码清空
                    user[0]['passStr'] = ''
                    return res(200, "登录成功！", {'user': user})
                else:
                    return res(400, "登录失败！", {'user': "验证码错误，请重新输入！"})
        else:
            return res(400, "登录失败！", {'err': "手机号未注册！"})


# 后台管理员登录
class AdminLogin(View):
    def get(self, request):
        # 响应数据
        return res(200, "OK", "操作成功！")

    def post(self, request):
        print(request.POST)
        # 获取登录参数
        username = request.POST.get("username")  # 用户名
        passStr = request.POST.get("passStr")  # 密码
        # 判断账号是否存在
        if AuthUsers.objects.filter(username=username).exists():
            # 获取登录的用户
            user = list(AuthUsers.objects.filter(username=username).values())
            # 判断密码是否正确
            pass_flag = pass_decode(passStr, user[0]['password'])
            if pass_flag:
                # 密码正确后，生成token
                token = get_admin_token(user[0])
                # 将token保存到用户信息中
                user[0]['token'] = "Bearer " + token
                # 将明文密码清空
                user[0]['passStr'] = ''
                return res(200, "登录成功！", {'user': user})
            else:
                # 登录失败
                return res(400, "登录失败！", {'err': "密码错误，请重新输入！"})
        else:
            # 登录失败
            return res(400, "登录失败！", {'err': "没有这个用户！"})
